<!DOCTYPE html>
<title>SharedWorker: </title>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<script>

function openWindow(url) {
  return new Promise(resolve => {
    const win = window.open(url, '_blank');
    add_completion_callback(() => win.close());
    window.onmessage = e => {
      assert_equals(e.data, 'LOADED');
      resolve(win);
    };
  });
}

promise_test(() => {
  const kScriptURL = 'resources/shared-worker-file-url-worker.js?same';
  const workers = [];

  // Ensure this document and script is hosted on file:// URL.
  assert_equals((new URL(location.href)).origin, 'file://');
  assert_equals((new URL(kScriptURL, location.href)).origin, 'file://');

  return new Promise(resolve => {
        workers.push(new SharedWorker(kScriptURL));
        workers[0].port.onmessage = resolve;
      })
    .then(msg_event => {
        assert_equals(msg_event.data.connection_count, 1);
        workers.push(new SharedWorker(kScriptURL));
        return new Promise(resolve => workers[1].port.onmessage = resolve);
      })
    .then(msg_event => {
        // The connection count should be 1 because the file: URL document
        // always connects to to a new shared worker instance.
        assert_equals(msg_event.data.connection_count, 1);
      });
}, 'A file: URL document should not connect to an existing shared worker.');

promise_test(() => {
  const kWindowURL = 'resources/shared-worker-file-url-window.html';
  const kScriptURL = 'resources/shared-worker-file-url-worker.js?different';
  let worker;

  // Ensure this document and script is hosted on file:// URL.
  assert_equals((new URL(location.href)).origin, 'file://');
  assert_equals((new URL(kScriptURL, location.href)).origin, 'file://');

  return openWindow(kWindowURL)
    .then(win => {
        const channel = new MessageChannel;
        win.postMessage(channel.port1, '*', [channel.port1]);
        return new Promise(resolve => channel.port2.onmessage = resolve);
      })
    .then(msg_event => {
        assert_equals(msg_event.data.connection_count, 1);
        worker = new SharedWorker(kScriptURL);
        return new Promise(resolve => worker.port.onmessage = resolve);
      })
    .then(msg_event => {
        // The connection count should be 1 because the file: URL document
        // always connects to to a new shared worker instance.
        assert_equals(msg_event.data.connection_count, 1);
      });
}, 'A file: URL document should not connect to an existing shared worker ' +
   'created by the other document in the different directory.');

</script>
